package renderer;

import java.nio.IntBuffer;

import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;

import sys.SysParam;
import texture.Texture;
import texture.TextureLoader;
import world.Crosshair;
import world.Vertex;

public class CrosshairRenderer {
	private static TextureLoader textureManager = TextureLoader.get();
	private static Texture texture;
	
	public static void render(Crosshair crosshair) {
		if (texture == null) {
			texture = textureManager.getTexture("assets/images/crosshair.png", false);
			int crossX = (int) (SysParam.SCREEN_WIDTH / 2 - texture.getImageWidth() / 2);
			int crossY = (int) (SysParam.SCREEN_HEIGHT / 2 - texture.getImageHeight() / 2);
			crosshair.createVertexes(crossX, crossY,1, 1);
			crosshair.buildRenderData();
		}

		GL13.glActiveTexture(GL13.GL_TEXTURE0);
		GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getTextureID());
		// Bind to the VAO that has all the information about the vertices
		GL20.glEnableVertexAttribArray(0);
		GL20.glEnableVertexAttribArray(1);
		GL20.glEnableVertexAttribArray(2);

		renderBuffer(crosshair.getVerticesBuffer());

		GL20.glDisableVertexAttribArray(0);
		GL20.glDisableVertexAttribArray(1);
		GL20.glDisableVertexAttribArray(2);
		GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
	}

	private static void renderBuffer(IntBuffer verticesBuffer) {
		int vboId = GL15.glGenBuffers();
		GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboId);
		GL15.glBufferData(GL15.GL_ARRAY_BUFFER, verticesBuffer, GL15.GL_STATIC_DRAW);

		GL20.glVertexAttribPointer(0, Vertex.SIZE_POSITION, GL11.GL_FLOAT, false, Vertex.STRIDE, Vertex.OFFSET_POSITION);
		GL20.glVertexAttribPointer(1, Vertex.SIZE_COLOR, GL11.GL_BYTE, false, Vertex.STRIDE, Vertex.OFFSET_COLOR);
		GL20.glVertexAttribPointer(2, Vertex.SIZE_TEXTURE, GL11.GL_FLOAT, false, Vertex.STRIDE, Vertex.OFFSET_TEXTURE);
		GL11.glDrawArrays(GL11.GL_QUADS, 0, 6);

		GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
		GL15.glDeleteBuffers(vboId);// this is very important to release the
									// memory
	}

}
